package org.zwy.gradetrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zwy.gradetrack.entity.GraduateSelfEvaluation;
import org.zwy.gradetrack.entity.Indicator;
import org.zwy.gradetrack.mapper.GraduateSelfEvaluationMapper;
import org.zwy.gradetrack.service.GraduateSelfEvaluationService;
import org.zwy.gradetrack.service.IndicatorService;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.math.BigDecimal;

/**
 * 毕业生自评服务实现类
 */
@Service
public class GraduateSelfEvaluationServiceImpl extends ServiceImpl<GraduateSelfEvaluationMapper, GraduateSelfEvaluation> implements GraduateSelfEvaluationService {

    @Autowired
    private IndicatorService indicatorService;

    @Override
    public Page<GraduateSelfEvaluation> pageEvaluations(Integer current, Integer size, Long graduateId, Long indicatorId) {
        LambdaQueryWrapper<GraduateSelfEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(graduateId != null, GraduateSelfEvaluation::getGraduateId, graduateId)
                .eq(indicatorId != null, GraduateSelfEvaluation::getIndicatorId, indicatorId)
                .orderByDesc(GraduateSelfEvaluation::getCreateTime);
        
        return page(new Page<>(current, size), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GraduateSelfEvaluation createEvaluation(GraduateSelfEvaluation evaluation) {
        // 检查指标点是否存在
        Indicator indicator = indicatorService.getById(evaluation.getIndicatorId());
        if (indicator == null) {
            throw new RuntimeException("指标点不存在");
        }

        // 检查是否已存在自评
        if (existsEvaluation(evaluation.getGraduateId(), evaluation.getIndicatorId())) {
            throw new RuntimeException("该毕业生对指标点的自评已存在");
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        evaluation.setCreateTime(now);
        evaluation.setUpdateTime(now);

        // 保存自评
        save(evaluation);
        return evaluation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GraduateSelfEvaluation updateEvaluation(Long id, GraduateSelfEvaluation evaluation) {
        // 检查自评是否存在
        GraduateSelfEvaluation existingEvaluation = getById(id);
        if (existingEvaluation == null) {
            throw new RuntimeException("自评数据不存在");
        }

        // 检查指标点是否存在
        Indicator indicator = indicatorService.getById(evaluation.getIndicatorId());
        if (indicator == null) {
            throw new RuntimeException("指标点不存在");
        }

        // 检查是否与其他自评冲突
        if (!existingEvaluation.getGraduateId().equals(evaluation.getGraduateId()) ||
            !existingEvaluation.getIndicatorId().equals(evaluation.getIndicatorId())) {
            if (existsEvaluation(evaluation.getGraduateId(), evaluation.getIndicatorId())) {
                throw new RuntimeException("该毕业生对指标点的自评已存在");
            }
        }

        // 更新自评
        evaluation.setId(id);
        evaluation.setUpdateTime(LocalDateTime.now());
        updateById(evaluation);
        return evaluation;
    }

    @Override
    public Map<String, Object> getStatistics(Long graduateId, Long indicatorId) {
        LambdaQueryWrapper<GraduateSelfEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(graduateId != null, GraduateSelfEvaluation::getGraduateId, graduateId)
                .eq(indicatorId != null, GraduateSelfEvaluation::getIndicatorId, indicatorId);

        List<GraduateSelfEvaluation> evaluations = list(wrapper);
        
        Map<String, Object> statistics = new HashMap<>();
        if (!evaluations.isEmpty()) {
            // 计算平均分
            double average = evaluations.stream()
                    .mapToDouble(e -> e.getScore().doubleValue())
                    .average()
                    .orElse(0.0);
            statistics.put("average", average);

            // 计算最高分
            double max = evaluations.stream()
                    .mapToDouble(e -> e.getScore().doubleValue())
                    .max()
                    .orElse(0.0);
            statistics.put("max", max);

            // 计算最低分
            double min = evaluations.stream()
                    .mapToDouble(e -> e.getScore().doubleValue())
                    .min()
                    .orElse(0.0);
            statistics.put("min", min);

            // 计算分数分布
            Map<Double, Long> distribution = evaluations.stream()
                    .collect(Collectors.groupingBy(
                            e -> e.getScore().doubleValue(),
                            Collectors.counting()
                    ));
            statistics.put("distribution", distribution);
        }

        return statistics;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchImport(List<GraduateSelfEvaluation> evaluations) {
        if (evaluations == null || evaluations.isEmpty()) {
            throw new RuntimeException("导入数据不能为空");
        }

        // 检查所有指标点是否存在
        Set<Long> indicatorIds = evaluations.stream()
                .map(GraduateSelfEvaluation::getIndicatorId)
                .collect(Collectors.toSet());
        
        List<Indicator> indicators = indicatorService.listByIds(indicatorIds);
        if (indicators.size() != indicatorIds.size()) {
            throw new RuntimeException("存在无效的指标点ID");
        }

        // 检查是否存在重复自评
        for (GraduateSelfEvaluation evaluation : evaluations) {
            if (existsEvaluation(evaluation.getGraduateId(), evaluation.getIndicatorId())) {
                throw new RuntimeException(
                    String.format("毕业生ID %d 对指标点ID %d 的自评已存在",
                        evaluation.getGraduateId(), evaluation.getIndicatorId())
                );
            }
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        evaluations.forEach(evaluation -> {
            evaluation.setCreateTime(now);
            evaluation.setUpdateTime(now);
        });

        // 批量保存
        saveBatch(evaluations);
    }

    @Override
    public boolean existsEvaluation(Long graduateId, Long indicatorId) {
        LambdaQueryWrapper<GraduateSelfEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GraduateSelfEvaluation::getGraduateId, graduateId)
                .eq(GraduateSelfEvaluation::getIndicatorId, indicatorId);
        return count(wrapper) > 0;
    }

    @Override
    public List<GraduateSelfEvaluation> getGraduateIndicatorEvaluations(Long graduateId, Long indicatorId) {
        LambdaQueryWrapper<GraduateSelfEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GraduateSelfEvaluation::getGraduateId, graduateId)
                .eq(GraduateSelfEvaluation::getIndicatorId, indicatorId)
                .orderByDesc(GraduateSelfEvaluation::getCreateTime);
        return list(wrapper);
    }

    @Override
    public BigDecimal getLatestEvaluationScore(Long indicatorId, Integer evaluationYear) {
        return baseMapper.selectLatestEvaluationScore(indicatorId, evaluationYear);
    }
} 